package com.example.thegreatwall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.thegreatwall.common.R;

import com.example.thegreatwall.entity.*;
import com.example.thegreatwall.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.annotations.Param;

import com.example.thegreatwall.entity.Comment;
import com.example.thegreatwall.entity.Order;
import com.example.thegreatwall.entity.ProductDetail;
import com.example.thegreatwall.service.CommentService;
import com.example.thegreatwall.service.OrderService;
import com.example.thegreatwall.service.ProductDetailService;
import com.example.thegreatwall.service.UsersService;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RequestMapping("/order")
@CrossOrigin(origins = "*") //无论什么源都可以访问  不写这个不允许跨域
@RestController
public class OrderController{
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private UsersService usersService;

    @Autowired
    private ProductService productService;

    @Autowired
    private TProductService tProductService;


    /**
     * 查询过期订单并作修改
     * @return
     */
    public String overdueOrder(){
        //获得当前时间
        Date now = new Date();
        long time1 = now.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatted = sdf.format(now);
        //筛选今天的，未支付状态的订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.like("create_time", formatted.substring(0, 10)).and(i->i.eq("status",0));
        List<Order> orders = orderService.list(orderQueryWrapper);
        int num=0;
        for (int i=0;i<orders.size();i++){//遍历订单
            Order order = orders.get(i);
            long time2 = order.getCreateTime().getTime()+(15 * 60 * 1000);//计算订单十五分钟后
            //判断时间
            if (time2 > time1) {//说明订单已过期
                order.setUpdateTime(now);
                order.setStatus(2);
                boolean b = orderService.updateById(order);
                if (b==true){
                    num++;
                }
            }
        };
        return "已修改过期订单："+num+"条";
    }


    @GetMapping(value = "updOrder")
    public String updOrder(@RequestParam int status,@RequestParam String orderNo){
        UpdateWrapper<Order> queryWrapper = new UpdateWrapper<>();
        queryWrapper.eq("order_no", orderNo).set("status", status);
        boolean update = orderService.update(queryWrapper);
        return update?"修改成功":"修改失败";
    }
    @GetMapping(value = "selstatus")
    public int selStatus(@RequestParam int detail_id,@RequestParam int user_id){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("detail_id", detail_id);
        queryWrapper.eq("user_id", user_id);
        queryWrapper.eq("status", 0);
        queryWrapper.select("order_id as id" );
        Order one = orderService.getOne(queryWrapper);
        System.out.println(one);
        if(one==null){
            return 1;
        }else {
            //有一笔未支付
            return 0;
        }
    }

    @GetMapping(value = "alldingdan")
    public R allDingdan(@RequestParam(required = false) Integer status,@RequestParam int user_id){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user_id) .orderByDesc("create_time");

        if (status != null) {
            if (status == 1) {
                // 使用or条件查询status=1或status=7
                queryWrapper.and(qw -> qw.eq("status", 1).or().eq("status", 7));
            } else {
                queryWrapper.eq("status", status);
            }
        }
        List<Order> orders = orderService.list(queryWrapper);
        for (Order order : orders) {
            if (order.getStatus()==3) {
                QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
                QueryWrapper<ProductDetail> productDetailQueryWrapper = new QueryWrapper<>();
                productDetailQueryWrapper.eq("product_detail_id",order.getDetailId());
                ProductDetail productDetail = productDetailService.getOne(productDetailQueryWrapper);
                commentQueryWrapper.eq("user_id", user_id).and(i->i.eq("product_id",productDetail.getProductId())).and(i->i.eq("product_type",productDetail.getProductType()));
                List<Comment> comment = commentService.list(commentQueryWrapper);
                if (comment.size()>0) {
                    order.setIsCommentFlag(1);
                }
            }
        }

        return new R().addDate("alldingdan",orders);
    }

    @GetMapping(value = "/updorderstatus")
    public int updorderstatus (@RequestParam String order_id){
       UpdateWrapper<Order> queryWrapper = new UpdateWrapper<>();
       queryWrapper.eq("order_id", order_id);
       queryWrapper.set("status", 4);
        boolean update = orderService.update(queryWrapper);
        return update?1:0;
    }


    @GetMapping(value = "getorder")
    public R getorder(@RequestParam String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order one = orderService.getOne(queryWrapper);
        return new R().addDate("one", one);
    }

    /**
     * 取消订单
     * @param order_id 订单编号
     * @return
     */
    @GetMapping("/cancelOrder")
    public R cancelOrder(@RequestParam("orderid") String order_id,@RequestParam("status") int status){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", order_id);
        Order one = orderService.getOne(queryWrapper);
        one.setStatus(status);
        boolean update = orderService.updateById(one);
        if (update) {
            return new R().addDate("msg","修改成功");
        }else {
            return new R().addDate("msg","修改失败");
        }
    }

    @PostMapping(value = "/insorder")
    public R insOrder(@RequestBody Order order){
        System.out.println("接收到的 order 参数：" + order); // 打印参数，排查是否真的为空
        R result = orderService.insOrder(order);
        // 直接返回这个结果给前端
        return result;
    }

    @GetMapping("/useQRCodes")
    public R useQRCodes(@RequestParam("orderNo") String orderNo) throws Exception {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        HashMap<String, Object> map = new HashMap<>();
        String json = "";
        Order one = orderService.getOne(queryWrapper);
        if (one==null){
            return new R().addDate("msg","订单不存在");
        }else {
            String tourdate = one.getTourdate();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startime = LocalDateTime.parse(tourdate.substring(0,16)+":00", formatter);
            LocalDateTime endtime = LocalDateTime.parse(tourdate.substring(0,11).concat(tourdate.substring(17))+":00", formatter);
            // 方式三：带偏移量的方式
            long startimestamp = startime.atZone(ZoneId.of("Asia/Shanghai"))
                    .toInstant()
                    .toEpochMilli();
            long endtimestamp = endtime.atZone(ZoneId.of("Asia/Shanghai"))
                    .toInstant()
                    .toEpochMilli();
            System.out.println("喵喵喵我是游玩时间"+startimestamp);
            System.out.println("我是结束时间！"+endtimestamp);
            LocalDateTime date = LocalDateTime.now();
            long timestamp2 = date.atZone(ZoneId.of("Asia/Shanghai"))
                    .toInstant()
                    .toEpochMilli();
            if (timestamp2>startimestamp && endtimestamp<timestamp2){ //处于游玩时间之内
                String openId = usersService.getOpenIdByUserId(one.getUserId());
                if (one.getStatus() == 3) {
                    map.put("msg", "二维码已被使用");
                    json = new ObjectMapper().writeValueAsString(map);
                    Session session = WxSocket.wxSessionMap.get(openId);
                    session.getBasicRemote().sendText(json);
                } else {
                    one.setStatus(3);
                    boolean update = orderService.updateById(one);
                    if (update) {
                        map.put("msg", "使用成功");
                        json = new ObjectMapper().writeValueAsString(map);
                        //是谁的二维码就还给谁好吗
                        Session session = WxSocket.wxSessionMap.get(openId);
                        session.getBasicRemote().sendText(json);
                    }
                }
            }else if (timestamp2<startimestamp){
                return new R().addDate("msg","还未到时间！");
            }else if(timestamp2>endtimestamp){
                return new R().addDate("msg","游玩时间已过");
            }
            System.out.println("现在："+timestamp2);

        }
        return new R().addDate("msg",map);
    }



    @GetMapping(value = "prevent")
    public R prevent(@RequestParam String orderno) {
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderno));
        ProductDetail pro = productDetailService.getOne(new QueryWrapper<ProductDetail>().eq("product_detail_id",order.getDetailId()));
        Product productId  = null;
        TProduct tProductId=null;
        if(pro.getProductType()==0) {
            productId = productService.getOne(new QueryWrapper<Product>().eq("product_id", pro.getProductId()));

        }else {
            tProductId = tProductService.getOne(new QueryWrapper<TProduct>().eq("t_product_id", pro.getProductId()));
        }
        //当商品下架了之后就不生成订单
        if (pro.getStatus() == 0 || (productId != null && productId.getStatus() == 0) || (tProductId != null && tProductId.getStatus() == 0)) {
            order.setStatus(2);
            orderService.updateById(order);
            return new R().setMsg("商品被下架");
        }

        return new R();
    }

}